﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Raize.CodeSiteLogging;
using System.Configuration;
using System.IO;
using System.Data;

namespace Pub
{

    public static class CDebug
    {

        public static Boolean B_DEBUG_SHOW = false;
        public static Boolean B_ERROR_SHOW = false;
        public static string sDebug_Show = "";
        public static string sError_Show = "";

        public static string sPath = "";
        public static string sFileName = "";
        //public static Stopwatch swatch = new Stopwatch();
        //public static List<Stopwatch> swList = new List<Stopwatch>();
        public static int i_Level = 0;

        static string s_div_l = "<div>";
        static string s_div_r = "</div>";


        public static List<Tree_Level> treeList = new List<Tree_Level>();

        /// <summary>
        /// 输出调试信息
        /// </summary>
        /// <param name="sMsg"></param>
        public static void Send(string sMsg)
        {



            if (sDebug_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            if (sMsg == null || sMsg == string.Empty) sMsg = "";
            CodeSite.Send(sMsg);
            sMsg = sMsg.Replace("<", "&lt");
            sMsg = sMsg.Replace(">", "&gt");
            sMsg = sMsg.Replace("\n", "<br>");
            writeLog("<div class='div_txt'>" + sMsg + "</div>");
            //Debug.WriteLine("___" + CPub.sNow() + "_________________________________________________________");
            //Debug.WriteLine(sMsg);
        }

        /// <summary>
        /// 输出调试信息
        /// </summary>
        /// <param name="sMsg"></param>
        /// <param name="sObj"></param>
        public static void Send(string sMsg, object sObj)
        {
            if (sError_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            CodeSite.Send(sMsg, sObj);
            sMsg = sMsg.Replace("<", "&lt");
            sMsg = sMsg.Replace(">", "&gt");
            sMsg = sMsg.Replace("\n", "<br>");
            writeLog("<div class='div_tit'>" + sMsg + "</div>");
            writeLog("<div class='div_obj'>" + sObj.ToString().Replace("\n", "<br>") + "</div>");
        }

        /// <summary>
        /// 输出调试信息
        /// </summary>
        /// <param name="sMsg"></param>
        /// <param name="sObj"></param>
        public static void Send(object sObj)
        {
            if (sError_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            CodeSite.Send(CPub.sNow(), sObj);
            writeLog("<div class='div_obj'>" + sObj.ToString().Replace("\n", "<br>") + "</div>");
        }

        public static void Send(DataSet ds1)
        {
            if (sError_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            if (ds1 != null && ds1.Tables.Count > 0)
            {

                DataTable dt1 = ds1.Tables[0];
                Send(dt1);
            }
        }

        public static void Send(DataSet ds1, int i_Top)
        {
            if (sError_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            if (ds1 != null && ds1.Tables.Count > 0)
            {

                DataTable dt1 = ds1.Tables[0];
                Send(dt1, i_Top);
            }
        }

        public static void Send(DataTable dt1)
        {
            Send(dt1, -1);
        }


        public static void Send(DataTable dt1, int i_Top)
        {
            if (sError_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;

            if (i_Top > dt1.Rows.Count) i_Top = dt1.Rows.Count;
            if (i_Top == -1) i_Top = dt1.Rows.Count;

            if (dt1 != null)
            {

                string sTit = "";
                for (int j = 0; j < dt1.Columns.Count; j++)
                {
                    if (j == 0)
                        sTit = dt1.Columns[j].Caption;
                    else
                        sTit += ",   " + dt1.Columns[j].Caption;
                }
                CodeSite.Send(sTit);
                writeLog("<div class='div_txt'>" + sTit + "</div>");

                for (int i = 0; i < i_Top; i++)
                {

                    string sCol = "";
                    DataRow dr1 = dt1.Rows[i];
                    for (int j = 0; j < dr1.ItemArray.Length; j++)
                    {
                        if (j == 0)
                            sCol = dr1[j].ToString();
                        else
                            sCol += ",  " + dr1[j].ToString();
                    }
                    CodeSite.Send(sCol);
                    writeLog("<div class='div_txt'>" + sCol + "</div>");
                }
            }
        }

        public static void Send(DataRow[] dr)
        {
            if (sError_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            if (dr != null)
            {
                for (int i = 0; i < dr.Length; i++)
                {
                    string sCol = "";
                    DataRow dr1 = dr[i];
                    for (int j = 0; j < dr1.ItemArray.Length; j++)
                    {
                        if (j == 0)
                            sCol = dr1[j].ToString();
                        else
                            sCol += ",  " + dr1[j].ToString();
                    }
                    CodeSite.Send(sCol);
                    writeLog("<div class='div_txt'>" + sCol + "</div>");
                }
            }
        }

        public static void Send(List<string> lst)
        {
            if (sError_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            if (lst != null)
            {
                for (int i = 0; i < lst.Count; i++)
                {
                    CodeSite.Send(lst[i]);
                    writeLog("<div class='div_txt'>" + lst[i] + "</div>");
                }
            }
        }


        public static void SendError(string sMsg)
        {
            if (sError_Show == string.Empty) init();
            if (B_ERROR_SHOW == false) return;
            CodeSite.SendError(sMsg);
            //CodeSite.Send(sMsg);
            sMsg = sMsg.Replace("<", "&lt");
            sMsg = sMsg.Replace(">", "&gt");
            sMsg = sMsg.Replace("\n", "<br>");
            writeLog("<div class='div_obj'>" + sMsg + "</div>");
        }

        public static void SendError(string sMsg, object obj1)
        {
            if (sError_Show == string.Empty) init();
            if (B_ERROR_SHOW == false) return;
            CodeSite.SendError(sMsg, new object[] { obj1 });
            writeLog("<div class='div_obj'>" + obj1.ToString().Replace("\n", "<br>") + "</div>");
        }


        public static void SendException(Exception e)
        {
            if (sError_Show == string.Empty) init();
            if (B_ERROR_SHOW == false) return;
            CodeSite.SendException(e);
            writeLog("<div class='div_obj'>" + e.ToString() + "</div>");
        }

        public static void SendException(string msg, Exception e)
        {
            if (sError_Show == string.Empty) init();
            if (B_ERROR_SHOW == false) return;
            CodeSite.SendException(msg, e);
            writeLog("<div class='div_obj'>" + e.ToString() + "</div>");
        }

        public static void SendToLiveView(string sMsg)
        {
            CodeSite.Send(sMsg);
        }


        /// <summary>
        /// 缩进
        /// </summary>
        /// <param name="s1"></param>
        public static void EnterMethod(string s1)
        {
            //swatch.Reset();
            //swatch.Start();

            if (treeList.Count > i_Level - 1)
            {
                Tree_Level treeLevel = new Tree_Level();
                treeLevel.iDeep = i_Level;
                treeLevel.sw = new Stopwatch();

                treeList.Add(treeLevel);
                i_Level++;
            }

            if (i_Level > 0)
            {
                treeList[i_Level - 1].sw.Reset();
                treeList[i_Level - 1].sw.Start();
            }

            if (sDebug_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            CodeSite.EnterMethod(s1);
            writeLog("" + s_div_l + "<div class='div_tit'>" + s1 + "</div>");
            writeLog("<div class='div_box'>");
        }

        /// <summary>
        /// 反缩进
        /// </summary>
        /// <param name="s1"></param>
        public static void ExitMethod(string s1)
        {
            //swatch.Stop();
            if (i_Level > 0) i_Level--;
            treeList[i_Level].sw.Stop();
            float f_UserTime = (float)treeList[i_Level].sw.ElapsedMilliseconds / 1000;

            if (sDebug_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            CodeSite.ExitMethod(s1 + " [" + f_UserTime + "]");
            writeLog("<div class='div_txt'>用时: " + f_UserTime + "s" + s_div_r + "</div>" + s_div_r + "");
        }

        /// <summary>
        /// 初始化日志文件
        /// </summary>
        public static void init()
        {
                sDebug_Show = ConfigurationManager.AppSettings["debug"];
                sError_Show = ConfigurationManager.AppSettings["error"];
                B_DEBUG_SHOW = Convert.ToBoolean(sDebug_Show);
                B_ERROR_SHOW = Convert.ToBoolean(sError_Show);

                if (Convert.ToBoolean(ConfigurationManager.AppSettings["log_w"]))
                {
                    //codesite
                    CodeSiteDestination dest = new CodeSiteDestination();
                    dest.LogFile.Active = true;
                    dest.LogFile.FileName = "CS_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".csl";
                    //dest.LogFile.FilePath = "$(MyDocs)";
                    dest.LogFile.FilePath = ConfigurationManager.AppSettings["logDir"] + "\\" + DateTime.Now.ToString("yyyyMM") + "\\" + DateTime.Now.ToString("dd") + "\\";
                    dest.Viewer.Active = true;
                    CodeSite.Destination = dest;

                    //自定义文本
                    sPath = ConfigurationManager.AppSettings["logDir"] + "\\" + DateTime.Now.ToString("yyyyMM") + "\\" + DateTime.Now.ToString("dd") + "\\";
                    sFileName = "Log_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".html";

                    CDebug.Send(sPath);

                    if (!Directory.Exists(sPath))
                        Directory.CreateDirectory(sPath);
                }

        }

        public static void writeLog(string sLog)
        {
            try
            {
                if (Convert.ToBoolean(CConfig.getPermite("log_w")) == false) return;

                string f1 = sPath + "\\" + sFileName;
                StreamWriter sw;
                //if (File.Exists(f1))
                //{
                //    sw = new StreamWriter(f1);
                //    //sw = File.AppendText(f1);
                //}
                //else
                //{
                sw = new StreamWriter(f1, true, Encoding.Default);
                //sw = File.CreateText(f1);
                FileInfo finf = new FileInfo(f1);
                if (finf.Length == 0)
                {
                    sw.WriteLine("<head>");
                    sw.WriteLine("<title>" + sFileName + "</title>");
                    sw.WriteLine("<link href='../../css/log.css' rel='stylesheet' type='text/css' />");
                    sw.WriteLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">");
                    sw.WriteLine("<script type=\"text/javascript\" src=\"../../jqe131/jquery-1.8.0.min.js\"></script>");
                    sw.WriteLine("<script type=\"text/javascript\" src=\"../../jqe131/jquery.easyui.min.js\"></script>");
                    sw.WriteLine("<script type=\"text/javascript\" src=\"../../css/log.js\"></script>");

                    sw.WriteLine("</head>");

                }

                //}

                sLog = sLog.Replace("\n", "<br>");
                sw.WriteLine(sLog);
                sw.Close();

                finf = new FileInfo(f1);
                //CDebug.SendToLiveView("log size = " + finf.Length);
            }
            catch (System.Exception ex)
            {
                CodeSite.SendError(ex.ToString());
            }

        }
    }


    public static class CDebug_II
    {

        public static Boolean B_DEBUG_SHOW = false;
        public static Boolean B_ERROR_SHOW = false;
        public static string sDebug_Show = "";
        public static string sError_Show = "";

        public static string sPath = "";
        public static string sFileName = "";
        //public static Stopwatch swatch = new Stopwatch();
        //public static List<Stopwatch> swList = new List<Stopwatch>();
        public static int i_Level = 0;

        static string s_li_l = "<li>";
        static string s_li_r = "</li>";

        public static List<Tree_Level> treeList = new List<Tree_Level>();

        /// <summary>
        /// 输出调试信息
        /// </summary>
        /// <param name="sMsg"></param>
        public static void Send(string sMsg)
        {



            if (sDebug_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            CodeSite.Send(sMsg);
            sMsg = sMsg.Replace("<", "&lt");
            sMsg = sMsg.Replace(">", "&gt");
            sMsg = sMsg.Replace("\n", "<br>");
            writeLog("" + s_li_l + "<font class='div_txt'>" + sMsg + "</font>" + s_li_r + "");
            //Debug.WriteLine("___" + CPub.sNow() + "_________________________________________________________");
            //Debug.WriteLine(sMsg);
        }

        /// <summary>
        /// 输出调试信息
        /// </summary>
        /// <param name="sMsg"></param>
        /// <param name="sObj"></param>
        public static void Send(string sMsg, object sObj)
        {
            if (sError_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            CodeSite.Send(sMsg, sObj);
            sMsg = sMsg.Replace("<", "&lt");
            sMsg = sMsg.Replace(">", "&gt");
            sMsg = sMsg.Replace("\n", "<br>");
            writeLog("" + s_li_l + "<font class='div_tit'>" + sMsg + "</font>" + s_li_r + "");
            writeLog("" + s_li_l + "<font class='div_obj'>" + sObj.ToString().Replace("\n", "<br>") + "</font>" + s_li_r + "");
        }

        /// <summary>
        /// 输出调试信息
        /// </summary>
        /// <param name="sMsg"></param>
        /// <param name="sObj"></param>
        public static void Send(object sObj)
        {
            if (sError_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            CodeSite.Send(CPub.sNow(), sObj);
            writeLog("" + s_li_l + "<font class='div_obj'>" + sObj.ToString().Replace("\n", "<br>") + "</font>" + s_li_r + "");
        }

        public static void Send(DataSet ds1)
        {
            if (sError_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            if (ds1 != null && ds1.Tables.Count > 0)
            {

                string sTit = "";
                for (int j = 0; j < ds1.Tables[0].Columns.Count; j++)
                {
                    if (j == 0)
                        sTit = ds1.Tables[0].Columns[j].Caption;
                    else
                        sTit += ",   " + ds1.Tables[0].Columns[j].Caption;
                }
                CodeSite.Send(sTit);
                writeLog("" + s_li_l + "<font class='div_txt'>" + sTit + "</font>" + s_li_r + "");

                for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
                {


                    string sCol = "";
                    DataRow dr1 = ds1.Tables[0].Rows[i];
                    for (int j = 0; j < dr1.ItemArray.Length; j++)
                    {
                        if (j == 0)
                            sCol = dr1[j].ToString();
                        else
                            sCol += ",  " + dr1[j].ToString();
                    }
                    CodeSite.Send(sCol);
                    writeLog("" + s_li_l + "<font class='div_txt'>" + sCol + "</font>" + s_li_r + "");
                }
            }
        }

        public static void Send(DataRow[] dr)
        {
            if (sError_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            if (dr != null)
            {
                for (int i = 0; i < dr.Length; i++)
                {
                    string sCol = "";
                    DataRow dr1 = dr[i];
                    for (int j = 0; j < dr1.ItemArray.Length; j++)
                    {
                        if (j == 0)
                            sCol = dr1[j].ToString();
                        else
                            sCol += ",  " + dr1[j].ToString();
                    }
                    CodeSite.Send(sCol);
                    writeLog("" + s_li_l + "<font class='div_txt'>" + sCol + "</font>" + s_li_r + "");
                }
            }
        }

        public static void Send(List<string> lst)
        {
            if (sError_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            if (lst != null)
            {
                for (int i = 0; i < lst.Count; i++)
                {
                    CodeSite.Send(lst[i]);
                    writeLog("" + s_li_l + "<font class='div_txt'>" + lst[i] + "</font>" + s_li_r + "");
                }
            }
        }


        public static void SendError(string sMsg)
        {
            if (sError_Show == string.Empty) init();
            if (B_ERROR_SHOW == false) return;
            CodeSite.SendError(sMsg);
            //CodeSite.Send(sMsg);
            sMsg = sMsg.Replace("<", "&lt");
            sMsg = sMsg.Replace(">", "&gt");
            sMsg = sMsg.Replace("\n", "<br>");
            writeLog("" + s_li_l + "<font class='div_obj'>" + sMsg + "</font>" + s_li_r + "");
        }

        public static void SendError(string sMsg, object obj1)
        {
            if (sError_Show == string.Empty) init();
            if (B_ERROR_SHOW == false) return;
            CodeSite.SendError(sMsg, new object[] { obj1 });
            writeLog("" + s_li_l + "<font class='div_obj'>" + obj1.ToString().Replace("\n", "<br>") + "</font>" + s_li_r + "");
        }


        public static void SendException(Exception e)
        {
            if (sError_Show == string.Empty) init();
            if (B_ERROR_SHOW == false) return;
            CodeSite.SendException(e);
            writeLog("" + s_li_l + "<font class='div_obj'>" + e.ToString() + "</font>" + s_li_r + "");
        }

        public static void SendException(string msg, Exception e)
        {
            if (sError_Show == string.Empty) init();
            if (B_ERROR_SHOW == false) return;
            CodeSite.SendException(msg, e);
            writeLog("" + s_li_l + "<font class='div_obj'>" + e.ToString() + "</font>" + s_li_r + "");
        }

        public static void SendToLiveView(string sMsg)
        {
            CodeSite.Send(sMsg);
        }


        /// <summary>
        /// 缩进
        /// </summary>
        /// <param name="s1"></param>
        public static void EnterMethod(string s1)
        {
            //swatch.Reset();
            //swatch.Start();

            if (treeList.Count > i_Level - 1)
            {
                Tree_Level treeLevel = new Tree_Level();
                treeLevel.iDeep = i_Level;
                treeLevel.sw = new Stopwatch();

                treeList.Add(treeLevel);
                i_Level++;
            }

            if (i_Level > 0)
            {
                treeList[i_Level - 1].sw.Reset();
                treeList[i_Level - 1].sw.Start();
            }

            if (sDebug_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            CodeSite.EnterMethod(s1);
            writeLog("" + s_li_l + "<span class='div_tit'>" + s1 + "</span>");
            writeLog("<ul class='div_box'>");
        }

        /// <summary>
        /// 反缩进
        /// </summary>
        /// <param name="s1"></param>
        public static void ExitMethod(string s1)
        {
            //swatch.Stop();
            if (i_Level > 0) i_Level--;
            treeList[i_Level].sw.Stop();
            float f_UserTime = (float)treeList[i_Level].sw.ElapsedMilliseconds / 1000;

            if (sDebug_Show == string.Empty) init();
            if (B_DEBUG_SHOW == false) return;
            CodeSite.ExitMethod(s1 + " [" + f_UserTime + "]");
            writeLog("" + s_li_l + "<font class='div_txt'>用时: " + f_UserTime + "s" + s_li_r + "</ul>" + s_li_r + "");
        }

        /// <summary>
        /// 初始化日志文件
        /// </summary>
        public static void init()
        {
            sDebug_Show = ConfigurationManager.AppSettings["debug"];
            sError_Show = ConfigurationManager.AppSettings["error"];
            B_DEBUG_SHOW = Convert.ToBoolean(sDebug_Show);
            B_ERROR_SHOW = Convert.ToBoolean(sError_Show);

            if (Convert.ToBoolean(ConfigurationManager.AppSettings["log_w"]))
            {
                //codesite
                CodeSiteDestination dest = new CodeSiteDestination();
                dest.LogFile.Active = true;
                dest.LogFile.FileName = "CS_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".csl";
                //dest.LogFile.FilePath = "$(MyDocs)";
                dest.LogFile.FilePath = ConfigurationManager.AppSettings["logDir"] + "\\" + DateTime.Now.ToString("yyyyMM") + "\\" + DateTime.Now.ToString("dd") + "\\";
                dest.Viewer.Active = true;
                CodeSite.Destination = dest;

                //自定义文本
                sPath = ConfigurationManager.AppSettings["logDir"] + "\\" + DateTime.Now.ToString("yyyyMM") + "\\" + DateTime.Now.ToString("dd") + "\\";
                sFileName = "Log_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".html";

                CDebug.Send(sPath);

                if (!Directory.Exists(sPath))
                    Directory.CreateDirectory(sPath);
            }
        }

        public static void writeLog(string sLog)
        {
            try
            {
                if (Convert.ToBoolean(CConfig.getPermite("log_w")) == false) return;

                string f1 = sPath + "\\" + sFileName;
                StreamWriter sw;
                //if (File.Exists(f1))
                //{
                //    sw = new StreamWriter(f1);
                //    //sw = File.AppendText(f1);
                //}
                //else
                //{
                sw = new StreamWriter(f1, true, Encoding.Default);
                //sw = File.CreateText(f1);
                FileInfo finf = new FileInfo(f1);
                if (finf.Length == 0)
                {
                    sw.WriteLine("<head>");
                    sw.WriteLine("<title>" + sFileName + "</title>");
                    sw.WriteLine("<link href='../../jqe131/log.css' rel='stylesheet' type='text/css' />");
                    sw.WriteLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">");
                    sw.WriteLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"../../jqe131/themes/default/easyui.css\">");
                    sw.WriteLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"../../jqe131/themes/icon.css\">");
                    //sw.WriteLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"../../jqe131/demo/demo.css\">");
                    sw.WriteLine("<script type=\"text/javascript\" src=\"../../jqe131/jquery-1.8.0.min.js\"></script>");
                    sw.WriteLine("<script type=\"text/javascript\" src=\"../../jqe131/jquery.easyui.min.js\"></script>");

                    sw.WriteLine("</head>");

                    sw.WriteLine("<ul id=\"root\" class=\"easyui-tree\" data-options=\"animate:true,dnd:true\">");
                }

                //}

                sLog = sLog.Replace("\n", "<br>");
                sw.WriteLine(sLog);
                sw.Close();

                finf = new FileInfo(f1);
                //CDebug.SendToLiveView("log size = " + finf.Length);
            }
            catch (System.Exception ex)
            {
                CodeSite.Send(ex.ToString());
                CodeSite.Send("保存日志出错", ex);
            }

        }
    }

    public struct Tree_Level
    {
        public Stopwatch sw;
        public int iCount;
        public int iDeep;
    }

}
